package ctrl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Observable;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import util.Constants.EVEData;
import data.EVEItem;
import data.EVESystem;

public class EVECentralCtrl extends Observable {

  public EVECentralCtrl() throws SAXException {
    _xmlReader = XMLReaderFactory.createXMLReader();
  }

  public void _retrieveMarketData(EVEItem item) throws MalformedURLException,
      IOException, SAXException {
    for (Iterator<EVESystem> IT = item.getItemMarketDataMap().keySet().iterator(); IT.hasNext();) {
      EVESystem system = (EVESystem) IT.next();
      _setupXMLParser(EVEData.Items, item, system);
    }
  }

  public void _retrieveMarketData(EVESystem system) throws IOException, SAXException {
    for (Iterator<EVEItem> IT = system.getSystemMarketDataMap().keySet().iterator(); IT.hasNext();) {
      EVEItem item = (EVEItem) IT.next();
      _setupXMLParser(EVEData.Systems, item, system);
    }
  }
  
  public void _setupXMLParser(EVEData data, EVEItem item, EVESystem system) throws IOException, SAXException{
    EVECentralXMLHandler xmlHandler = new EVECentralXMLHandler(data, item, system);
    _xmlReader.setContentHandler(xmlHandler);
    _xmlReader.parse(new InputSource(new URL(_EVECentralURL + "?typeid=" + item.getItemID() + "&usesystem=" + system.getSystemID()).openStream()));
  }

  private String    _EVECentralURL = "http://api.eve-central.com/api/marketstat";
  private XMLReader _xmlReader;

}

// http://api.eve-central.com/api/marketstat?typeid=34&usesystem=30000142
